﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PKURG.CostSplit.Business;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class SCMain : System.Web.UI.Page
{
    public string ProjectName { get; set; }
    public string StageName { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            InitData();
        }


    }

    private void InitData()
    {
        int id = 0;
        string idString = Request["Id"];
        if (string.IsNullOrEmpty(idString) || !int.TryParse(idString, out id))
        {
            Common.GoErrorPage();
            return;
        }

        List<dynamic> stageInfos = Project.GetProjectStageInfo(id);
        if (stageInfos.Count <= 0 || stageInfos[0].rCount == "0")
        {
            Common.GoErrorPage();
            return;
        }

        ProjectName = stageInfos[0].ProjectName;
        StageName = stageInfos[0].StageName;

        LoadSpilteData(id);
        LoadMingData(id);

        //ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(UpdatePanel), "a", "<script>alert('s');</script>",false);
    }

    public List<dynamic> AccountInfos { get; set; }

    private void LoadSpilteData(int id)
    {
        List<dynamic> infos = DetailSplit.GetProjectStageAccountData(id);
        // throw new NotImplementedException();
        AccountInfos = infos;

        decimal total_contract_amt = 0;
        decimal total_sj_amount = 0;
        decimal total_qs_amount = 0;

        int currentRowIndex = 7;

        foreach (var item in infos)
        {
            HtmlTableRow row = new HtmlTableRow();
            row.Cells.Add(new HtmlTableCell()
            {
                Align = "Left",
                InnerText = string.Format("成本.{0}", item.Name)
            });
            row.Cells.Add(new HtmlTableCell()
            {
                InnerText = item.Des.Replace(item.Name + ".", "")
            });
            if (item.IsLeaf == "1")
            {
                row.Cells.Add(new HtmlTableCell()
                {
                    InnerHtml = string.Format("<div row_total='{1}'>{0}</div>", decimal.Parse(string.IsNullOrEmpty(item.contract_amt) ? "0" : item.contract_amt).ToDisplayString()
                    , currentRowIndex++)
                });
                row.Cells.Add(new HtmlTableCell()
                {
                    InnerText = decimal.Parse(string.IsNullOrEmpty(item.sj_amount) ? "0" : item.sj_amount).ToDisplayString()
                });
                row.Cells.Add(new HtmlTableCell()
                {
                    InnerText = decimal.Parse(string.IsNullOrEmpty(item.qs_amount) ? "0" : item.qs_amount).ToDisplayString()
                });
                row.Cells.Add(new HtmlTableCell()
                {
                    InnerText = ""
                });
                row.Cells.Add(new HtmlTableCell()
                {
                    InnerText = ""
                });
                //row.Cells.Add(new HtmlTableCell()
                //{
                //    InnerText = ""
                //});

                //total_contract_amt += decimal.Parse(string.IsNullOrEmpty(item.contract_amt)?"0":item.contract_amt);
                total_contract_amt += AccountInfos.Sum(x => (Decimal)(ConvertStringToDec(x.contract_amt)));

                total_sj_amount += decimal.Parse(string.IsNullOrEmpty(item.sj_amount) ? "0" : item.sj_amount);
                total_qs_amount += decimal.Parse(string.IsNullOrEmpty(item.qs_amount) ? "0" : item.qs_amount);

            }
            else
            {
                //var ss = item.Name.ToString();
                //var ii = AccountInfos.Where(x => x.Name.Contains(item.Name + "."));
                row.Cells.Add(new HtmlTableCell()
                {
                    InnerText = AccountInfos.Where(x => x.Name.Contains(item.Name + "."))
                    .Sum(x => (Decimal)(ConvertStringToDec(x.contract_amt))).ToDisplayString()
                });
                row.Cells.Add(new HtmlTableCell()
                {
                    InnerText = AccountInfos.Where(x => x.Name.Contains(item.Name + "."))
                    .Sum(x => (Decimal)(ConvertStringToDec(x.sj_amount))).ToDisplayString()
                });
                row.Cells.Add(new HtmlTableCell()
                {
                    InnerText = AccountInfos.Where(x => x.Name.Contains(item.Name + "."))
                    .Sum(x => (Decimal)(ConvertStringToDec(x.qs_amount))).ToDisplayString()
                });
                row.Cells.Add(new HtmlTableCell()
                {
                    InnerText = ""
                });
                row.Cells.Add(new HtmlTableCell()
                {
                    InnerText = ""
                });
            }
            MainTable.Rows.Add(row);

        }


        HtmlTableRow sumRow = new HtmlTableRow();
        sumRow.Cells.Add(new HtmlTableCell()
        {
            InnerText = "SUM1"
        });
        sumRow.Cells.Add(new HtmlTableCell()
        {
            InnerText = "开发成本小计(成本A～H）"
        });
        sumRow.Cells.Add(new HtmlTableCell()
        {
            InnerText = total_contract_amt.ToDisplayString()
        });
        sumRow.Cells.Add(new HtmlTableCell()
        {
            InnerText = total_sj_amount.ToDisplayString()
        });
        sumRow.Cells.Add(new HtmlTableCell()
        {
            InnerText = total_qs_amount.ToDisplayString()
        });

        sumRow.Cells.Add(new HtmlTableCell()
        {
            InnerText = ""//结算金额
        });
        sumRow.Cells.Add(new HtmlTableCell()
        {
            InnerText = ""//校核
        });

        MainTable.Rows.Add(sumRow);

        HtmlTableRow sumRow2 = new HtmlTableRow();
        sumRow2.Cells.Add(new HtmlTableCell()
        {
            InnerText = "各楼栋实际已发生成本汇总",
            ColSpan = 2
        });
        for (int index = 0; index < 5; index++)
        {
            sumRow2.Cells.Add(new HtmlTableCell());
        }
        MainTable.Rows.Add(sumRow2);

        HtmlTableRow sumRow3 = new HtmlTableRow();
        sumRow3.Cells.Add(new HtmlTableCell()
        {
            InnerText = "销售面积单方成本",
            ColSpan = 2
        });
        for (int index = 0; index < 5; index++)
        {
            sumRow3.Cells.Add(new HtmlTableCell());
        }
        MainTable.Rows.Add(sumRow3);

    }

    public decimal ConvertStringToDec(dynamic s)
    {
        if (string.IsNullOrEmpty(s))
        {
            return 0;
        }
        string ss = s.ToString();
        return decimal.Parse(ss);
    }

    private void LoadMingData(int id)
    {
        List<dynamic> detailInfos = DetailSplit.GetDetailSplitInfoAtOnce(id, 1);


        List<dynamic> infos = DetailSplit.GetProjectStageMData(id);
        // throw new NotImplementedException();

        var groupData = infos.GroupBy(x => x.FName).ToDictionary(x => x.Key, x => x.ToList());

        //StateBag bag = new StateBag();
        //bag.Add("class", "table_cell_m");
        //AttributeCollection attributes = new AttributeCollection(bag);


        foreach (var item in groupData)
        {
            var childGroupData = item.Value.GroupBy(y => y.SName).ToDictionary(x => x.Key, x => x.ToList()); ;

            int subItemIndex = 0;
            foreach (var subItem in childGroupData)
            {
                foreach (var buidingItem in subItem.Value.OrderBy(x => x.Name).ToList())
                {
                    MainTable.Rows[2].Cells.Add(new HtmlTableCell()
                    {
                        InnerHtml = string.Format("<div class='table_tb_m'>{0}</div>", buidingItem.Name),
                        Align = "Center"

                    });
                    MainTable.Rows[3].Cells.Add(new HtmlTableCell()
                    {
                        InnerHtml = "<div class='table_tb_m'>销售面积（㎡）</div>",
                        Align = "Center"
                    });
                    MainTable.Rows[4].Cells.Add(new HtmlTableCell()
                    {
                        InnerHtml = string.Format("<div class='table_tb_m'>{0}</div>", decimal.Parse(buidingItem.Area).ToString("F2")),
                        Align = "Center"
                    });
                    MainTable.Rows[5].Cells.Add(new HtmlTableCell()
                    {
                        InnerHtml = "<div class='table_tb_m'>销售面积单方成本</div>",
                        Align = "Center"
                    });



                    ///添加单元格
                    int startIndex = 6;
                    decimal sumCost = 0;
                    foreach (var accountItem in AccountInfos)
                    {
                        if (accountItem.IsLeaf == "1")
                        {
                            dynamic detailItemInfo = detailInfos.Where(x => x.Account == accountItem.Id && x.BuildingId == buidingItem.Id).SingleOrDefault();
                            if (detailItemInfo == null)
                            {
                                detailItemInfo = new
                                {
                                    Id = Guid.NewGuid(),

                                    Value = 0.0
                                };
                                bool isCreateOk = DetailSplit.CreateDetailItemInfo(detailItemInfo.Id, Guid.Parse(accountItem.Id), Guid.Parse(buidingItem.Id), 1);
                            }
                            MainTable.Rows[startIndex].Cells.Add(new HtmlTableCell()
                            {
                                //InnerHtml = "<input type='text' value='"+buidingItem.Name+"'/>",
                                InnerHtml = string.Format("<input type='text' value='{0}' name='dsc_{1}' class='csinput' row='{2}'/>", detailItemInfo.Value, detailItemInfo.Id, startIndex),
                                //InnerHtml="aa",
                                Align = "Center",
                                ID = detailItemInfo.Id
                            });

                            sumCost += decimal.Parse(detailItemInfo.Value);
                        }
                        else
                        {


                            MainTable.Rows[startIndex].Cells.Add(new HtmlTableCell()
                            {
                                InnerHtml = detailInfos.Where(x => x.AccountName.Contains(accountItem.Name + ".") && x.BuildingId == buidingItem.Id).Sum(x => (Decimal)(ConvertStringToDec(x.Value))).ToDisplayString(),
                                Align = "Center"
                            });
                        }
                        startIndex++;
                        //if (startIndex==7)
                        //{
                        //    break;
                        //}



                    }
                    //sum
                    MainTable.Rows[startIndex++].Cells.Add(new HtmlTableCell()
                                                {
                                                    InnerHtml = "",
                                                    Align = "Center"
                                                });
                    MainTable.Rows[startIndex++].Cells.Add(new HtmlTableCell()
                                                {
                                                    InnerHtml = sumCost.ToString(),
                                                    Align = "Center"
                                                });
                    MainTable.Rows[startIndex].Cells.Add(new HtmlTableCell()
                                                {
                                                    InnerHtml = (sumCost / decimal.Parse(buidingItem.Area)).ToDisplayString(),
                                                    Align = "Center"
                                                });

                    ///
                }
                MainTable.Rows[1].Cells.Add(new HtmlTableCell()
                {
                    InnerHtml = string.Format(@"<div class='table_td_m_type' data='{1}' {2}>
                    <img class='left' /><span>{0}</span><img class='right'/></div>",
                     subItem.Key, subItemIndex, subItemIndex == 0 ? "" : "style='display:none'"),
                    //InnerText = string.Format("{0}", subItem.Key),
                    ColSpan = subItem.Value.Count,
                    Align = "Center",
                    VAlign = "Middle",

                });
                subItemIndex++;
            }
            MainTable.Rows[0].Cells.Add(new HtmlTableCell()
            {
                InnerHtml = string.Format("<div class='table_td_m_type'>{0}</div>", item.Key),
                ColSpan = item.Value.Count,
                Align = "Center"
            });
        }
        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
        MainTable.RenderControl(hw);
        tw.ToString();
        MainTable.Visible = false;

        //MainTable.Rows[0].Cells[0].Controls.Add(new 
    }

    private void LoadMingData(int id, int index)
    {
        List<dynamic> infos = DetailSplit.GetProjectStageMData(id);
        // throw new NotImplementedException();

        //  var groupData = infos.GroupBy(x => x.FName).ToDictionary(x => x.Key, x => x.ToList());

        var childGroupData = infos.GroupBy(y => y.SName).ToDictionary(x => x.Key, x => x.ToList()); ;

        if (index < 0)
        {
            index = 0;
        }
        else if (index >= childGroupData.Count)
        {
            index = childGroupData.Count - 1;
        }
        var item = childGroupData.ElementAt(index);

        int subItemIndex = 0;

        foreach (var buidingItem in item.Value.OrderBy(x => x.Name).ToList())
        {
            MainTable.Rows[2].Cells.Add(new HtmlTableCell()
            {
                InnerHtml = string.Format("<div class='table_tb_m'>{0}</div>", buidingItem.Name),
                Align = "Center"

            });
            MainTable.Rows[3].Cells.Add(new HtmlTableCell()
            {
                InnerHtml = "<div class='table_tb_m'>销售面积（㎡）</div>",
                Align = "Center"
            });
            MainTable.Rows[4].Cells.Add(new HtmlTableCell()
            {
                InnerHtml = string.Format("<div class='table_tb_m'>{0}</div>", decimal.Parse(buidingItem.Area).ToString("F2")),
                Align = "Center"
            });
            MainTable.Rows[5].Cells.Add(new HtmlTableCell()
            {
                InnerHtml = "<div class='table_tb_m'>销售面积单方成本</div>",
                Align = "Center"
            });



            ///添加单元格
            int startIndex = 6;
            foreach (var accountItem in AccountInfos)
            {
                MainTable.Rows[startIndex].Cells.Add(new HtmlTableCell()
                {
                    InnerHtml = "<input type='text'/>",
                    Align = "Center"
                });
                startIndex++;
            }
            ///
            subItemIndex++;
        }


        MainTable.Rows[1].Cells.Add(new HtmlTableCell()
        {
            InnerHtml = string.Format(@"<div class='table_td_m_type' curr='{1}' total='{3}' {2}>
                            <img class='left' /><span>{0}</span><img class='right'/></div>",
             item.Key, index, index == 0 ? "" : "", childGroupData.Count),
            //InnerText = string.Format("{0}", subItem.Key),
            ColSpan = item.Value.Count,
            Align = "Center",
            VAlign = "Middle",

        });
        MainTable.Rows[0].Cells.Add(new HtmlTableCell()
         {
             InnerHtml = string.Format("<div class='table_td_m_type'>{0}</div>", item.Value[0].FName),
             ColSpan = item.Value.Count,
             Align = "Center"
         });
    }

    private void LoadSum()
    {
        int startIndex = 7;

    }

    public bool IsSave = false;

    protected void btnDoEvent_Click(object sender, EventArgs e)
    {
        int id = 0;
        string idString = Request["Id"];
        if (string.IsNullOrEmpty(idString) || !int.TryParse(idString, out id))
        {
            Common.GoErrorPage();
            return;
        }
        if (hidEType.Value == "ChangeIndex")
        {
            LoadSpilteData(id);
            LoadMingData(id, int.Parse(hidParams.Value));
        }

    }

    protected void btnSave_Click(object sender, EventArgs e)
    {

        int id = 0;
        string idString = Request["Id"];
        if (string.IsNullOrEmpty(idString) || !int.TryParse(idString, out id))
        {
            Common.GoErrorPage();
            return;
        }

        List<dynamic> detailInfos = DetailSplit.GetDetailSplitInfoAtOnce(id, 1);

        string[] updateKeys = Request.Form.AllKeys.Where(x => x.StartsWith("dsc_")).ToArray();
        foreach (var item in updateKeys)
        {
            //if (item.StartsWith("dsc_"))
            //{

            dynamic detailInfo = detailInfos.Where(x => x.Id == item.Replace("dsc_", "")).SingleOrDefault();
            if (detailInfo == null)
            {
                //保存失败
            }

            string[] values = Request.Form[item].Split(',');
            decimal value = decimal.Parse(values.Last() == "" ? "0" : values.Last());
            if (detailInfo.Value != value.ToString())
            {//只更新变更值
                Guid itemId = Guid.Parse(item.Replace("dsc_", ""));
                DetailSplit.UpDateDetailItemInfo(itemId, value);
            }
            //}
        }

        InitData();
        IsSave = true;
    }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        //string aa = "<input type='text' value='sss' name='dsc_{1}' class='csinput' row='{2}'";

        //Common.StripHTML(aa);

        InitData();

        string fileName = string.Format("{0}({1})", ProjectName, StageName);

        NPOI.HSSF.UserModel.HSSFWorkbook hssfworkbook = new NPOI.HSSF.UserModel.HSSFWorkbook();
        NPOI.SS.UserModel.ISheet sheet = hssfworkbook.CreateSheet(fileName);

        int freezeColCount = 7;
        int colCount = MainTable.Rows[2].Cells.Count;//真正列数
        //创建表头
        NPOI.SS.UserModel.IRow headRow = sheet.CreateRow(0);
        string[] freezeCol = { "科目编码", "成本科目", "合同金额", "设计变更", "签证洽商", "结算金额", "校核" };
        for (int headColIndex = 0; headColIndex < freezeColCount; headColIndex++)
        {
            NPOI.SS.UserModel.ICell cell = headRow.CreateCell(headColIndex);
            cell.SetCellValue(freezeCol[headColIndex]);
        }

        int exportTableColIndex = freezeColCount;
        for (int headColIndex = freezeColCount; headColIndex < colCount; headColIndex++)
        {
            sheet.SetColumnHidden((short)exportTableColIndex, true);
            NPOI.SS.UserModel.ICell hiddenCell = headRow.CreateCell(exportTableColIndex++);
            hiddenCell.SetCellValue("");

            NPOI.SS.UserModel.ICell cell = headRow.CreateCell(exportTableColIndex++);
            cell.SetCellValue(Common.StripHTML(MainTable.Rows[2].Cells[headColIndex - 2].InnerText));
        }

        //数据
        int startIndex = 7;
        int endIndex = MainTable.Rows.Count - 3;
        int sheetRowIndex = 1;



        for (int index = startIndex; index < endIndex; index++)
        {
            NPOI.SS.UserModel.IRow row = sheet.CreateRow(sheetRowIndex++);
            for (int colIndex = 0; colIndex < 7; colIndex++)
            {
                NPOI.SS.UserModel.ICell cell = row.CreateCell(colIndex);
                cell.SetCellValue(Common.StripHTML(MainTable.Rows[index].Cells[colIndex].InnerText));
            }

            exportTableColIndex = freezeColCount;
            for (int colIndex = 7; colIndex < MainTable.Rows[8].Cells.Count; colIndex++)
            {
                NPOI.SS.UserModel.ICell hiddenCell = row.CreateCell(exportTableColIndex++);
                hiddenCell.SetCellValue(MainTable.Rows[index].Cells[colIndex].ID);

                NPOI.SS.UserModel.ICell cell = row.CreateCell(exportTableColIndex++);
                cell.SetCellValue(Common.StripHTML(MainTable.Rows[index].Cells[colIndex].InnerText));
            }
        }


        string excelFilePath = Path.Combine(Server.MapPath("~/Files/Export/"), fileName + ".xls");

        //转为字节数组  
        System.IO.MemoryStream stream = new System.IO.MemoryStream();
        hssfworkbook.Write(stream);
        var buf = stream.ToArray();
        File.WriteAllBytes(excelFilePath, buf);

        Response.TransmitFile(excelFilePath);
    }
}